﻿using DotNetOpenAuth.AspNet.Clients;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;
using Inovout.Runtime;
using System.Collections.Generic;
using System.Net.Mail;

namespace Inovout.Account.Web.OpenIdClients
{
    public class MailAccountClient : OpenIdClient
    {
        public MailAccountClient()
            : this(GetMailAccountProviderEndpoint())
        {
        }

        public const string ProviderName = "mail";
        public const string SumPoerProviderName = "samples.cn";
        public const string MailAccountProviderEndpoint = "MailAccountProviderEndpoint";

        private static string GetMailAccountProviderEndpoint()
        {
            IApplication application = ComponentRegistry.Resolve<IApplication>();
            string url = null;
            if (application.Settings.Contains(MailAccountProviderEndpoint))
            {
                url = application.Settings[MailAccountProviderEndpoint].ToString();
            }
            else
            {
                url = "http://sumpoweraccount.sumapp.cn/OpenId";
            }
             if (url.Contains("?"))
            {
                url += "&force_login=1";
            }
            else
            {
                url += "?force_login=1";
            }
            return url;
        }
        internal MailAccountClient(Identifier providerIdentifier)
            : base(ProviderName, providerIdentifier)
            //  internal MailAccountClient(Identifier providerIdentifier)
            //: base("samples", providerIdentifier)
        { }

        protected override Dictionary<string, string> GetExtraData(IAuthenticationResponse response)
        {
            var claimsResponse = response.GetExtension<ClaimsResponse>();
            if (claimsResponse != null)
            {

                var friendlyidentifier = response.FriendlyIdentifierForDisplay;
             
                Dictionary<string, string> dictionary = new Dictionary<string, string>();
                dictionary.Add("username", claimsResponse.FullName);
                dictionary.Add("email", claimsResponse.Email);

                return dictionary;
            }

            return null;
        }
        protected override void OnBeforeSendingAuthenticationRequest(IAuthenticationRequest request)
        {
            //FetchRequest fetchRequest = new FetchRequest();
            //AXUtilities.AddRequired(fetchRequest.Attributes, WellKnownAttributes.Name.FullName);
            //request.AddExtension(fetchRequest);

            request.AddExtension(new ClaimsRequest
            {
                FullName = DemandLevel.Require,
                Email = DemandLevel.Require
            });
        }
    }
}